package com.sun.dream.fish.secret.mixture;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.*;
import java.util.Arrays;

public class RSAKEMExample {
    public static void main(String[] args) {
        try {
            // 生成密钥对
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            SecureRandom secureRandom = new SecureRandom();
            keyPairGenerator.initialize(2048, secureRandom);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();

            // 初始化加密密钥
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(256);
            SecretKey secretKey = keyGenerator.generateKey();

            // 使用接收方的公钥进行密钥封装
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = cipher.wrap(secretKey);

            // 使用接收方的私钥进行解封
            cipher.init(Cipher.UNWRAP_MODE, privateKey);
            Key unwrappedKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

            // 验证解封过程是否成功
            if (Arrays.equals(secretKey.getEncoded(), unwrappedKey.getEncoded())) {
                System.out.println("Key encapsulation and decapsulation successful!");
            } else {
                System.out.println("Key encapsulation and decapsulation failed!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}